import 'dart:_http';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

/// 登陆页面
class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return LoginState();
  }
}

class LoginState extends State<LoginPage> {
  final TextEditingController _nameController = new TextEditingController();
  final TextEditingController _pwdController = new TextEditingController();

  String _username;
  String _pwd;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getUserName();
    _getPwd();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text(
          '登录',
          style: TextStyle(
            color: Colors.white,
          ),
        ),
        elevation: 5.0,
        titleSpacing: 1.0,
        iconTheme: IconThemeData(color: Colors.white),
      ),
      body: Center(
        child: Container(
          height: 200.0,
          alignment: AlignmentDirectional.center,
          margin: EdgeInsets.all(10.0),
          padding: EdgeInsets.only(left: 40.0, right: 40.0),
          child: Column(
            children: <Widget>[
              _getIconWidget(),
              _getTextFieldWidget('用户名', _nameController, _username),
              _getTextFieldWidget('密码', _pwdController, _pwd),
              _getButtons(),
            ],
          ),
        ),
      ),
    );
  }

  CircleAvatar _getIconWidget() {
    return CircleAvatar(
      backgroundColor: Colors.blue,
      child: Icon(
        Icons.person,
        color: Colors.white,
      ),
    );
  }

  TextField _getTextFieldWidget(
      String title, TextEditingController controller, String hint) {
    return TextField(
      decoration: InputDecoration(
        labelText: title,
        labelStyle: TextStyle(color: Colors.blue),
        contentPadding: EdgeInsets.all(4.0),
      ),
      controller: controller,
    );
  }

  Row _getButtons() {
    return Row(
      children: <Widget>[
        RaisedButton(
          child: Text(
            '登陆',
            style: TextStyle(color: Colors.white),
          ),
          color: Colors.blue,
          onPressed: () {
            print('触发点击事件');
            _handlerPostFormDataMethod(loginApi, true);
          },
        ),
        Expanded(child: Text('')),
        RaisedButton(
          child: Text(
            '注册',
            style: TextStyle(color: Colors.white),
          ),
          color: Colors.blue,
          onPressed: () {
            _handlerPostFormDataMethod(registerApi, false);
          },
        ),
      ],
    );
  }

  _handlerPostMethod(String api, bool isLog) async {
    String name = _nameController.value.text;
    String pwd = _pwdController.value.text;
    if (name == null) {
      print('name is null');
      return;
    }
    if (pwd == null) {
      print('pwd is null');
      return;
    }
    String currentApi;
    if (isLog) {
      currentApi = api + "?username=$name+&password=$pwd";
    } else {
      currentApi = api + "?username=$name&password=$pwd&repassword=$pwd";
    }
    Dio dio = new Dio();
    await dio
        .post(
      currentApi,
    )
        .then((value) {
      print('请求成功');
      print(value);
      //是登陆
      if (value.data['errorCode'] == 0) {
        print('登陆成功');
        _saveUserData(value);
      } else {
        print('密码错误');
      }
    }).catchError((error) {
      print('出现错误');
      print(error);
    }).whenComplete(() {});
  }

  ///post的数据  formData post 用以提交的数据
  _handlerPostFormDataMethod(String api, bool isLog) async {
    String name = _nameController.value.text;
    String pwd = _pwdController.value.text;
    if (name == null) {
      print('name is null');
      return;
    }
    if (pwd == null) {
      print('pwd is null');
      return;
    }
    Dio dio = new Dio();
    FormData formData;
    if (isLog) {
      formData = FormData.from({'username': name, 'password': pwd});
    } else {
      formData =
          FormData.from({'username': name, 'password': pwd, 'repassword': pwd});
    }
    dio.options.baseUrl = api;
    await dio
        .post(
      '',
      data: formData,
    )
        .then((value) {
      print('请求成功');
      print(value);
      //是登陆
      if (value.data['errorCode'] == 0) {
        print('登陆成功');
        _saveUserData(value);
      } else {
        print('密码错误');
      }
    }).catchError((error) {
      print('出现错误');
      print(error);
    }).whenComplete(() {});
  }

  _saveUserData(Response value) async {
    print('保存信息');
    SharedPreferences sp = await SharedPreferences.getInstance();
    sp.setString('userName', value.data['data']['username']);
    sp.setString('pwd', value.data['data']['password']);

    HttpHeaders header = value.headers;
    String cookieHeader = header[HttpHeaders.setCookieHeader].toString();
    sp.setString('cookie', cookieHeader);

    ///退出当前页面
    bool success = true;
    Navigator.of(context).pop(success);
  }

  _getUserName() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    _username = sp.getString('userName');
    setState(() {
      _nameController.text = _username;
    });
  }

  _getPwd() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    _pwd = sp.getString('pwd');
    setState(() {
      _pwdController.text = _pwd;
      print('获取信息$_pwd');
    });
  }
}

///[data]={data: {collectIds: [], email: , icon: , id: 9931, password: 147258369, token: , type: 0, username: 哦啦吐了吃饭了}, errorCode: 0, errorMsg: }
String loginApi = 'http://www.wanandroid.com/user/login'; //登陆

///{collectIds: [], email: , icon: , id: 9931, password: 147258369, token: , type: 0, username: 哦啦吐了吃饭了}, errorCode: 0, errorMsg: }
String registerApi = 'http://www.wanandroid.com/user/register'; //注册
